// API基础URL
const API_BASE_URL = '/api';

// DOM元素
let loginSection, mainContent, loginForm, logoutBtn, backBtn;
let outboundForm, goodsIdInput, customerInput, quantityInput, expectedPickupDateInput, operatorInput, notesInput, resetBtn;

// JWT令牌
let authToken = localStorage.getItem('authToken');

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，开始初始化...');
    
    // 初始化DOM元素
    initializeDOMElements();
    
    // 检查用户是否已登录
    if (authToken) {
        showMainContent();
        setDefaultDate();
    } else {
        showLoginSection();
    }
    
    // 绑定事件监听器
    bindEventListeners();
});

// 初始化DOM元素
function initializeDOMElements() {
    // 认证相关元素
    loginSection = document.getElementById('loginSection');
    mainContent = document.getElementById('mainContent');
    loginForm = document.getElementById('loginForm');
    logoutBtn = document.getElementById('logoutBtn');
    backBtn = document.getElementById('backBtn');

    // 表单元素
    outboundForm = document.getElementById('outboundForm');
    goodsIdInput = document.getElementById('goodsId');
    customerInput = document.getElementById('customer');
    quantityInput = document.getElementById('quantity');
    expectedPickupDateInput = document.getElementById('expectedPickupDate');
    operatorInput = document.getElementById('operator');
    notesInput = document.getElementById('notes');
    resetBtn = document.getElementById('resetBtn');
}

// 绑定事件监听器
function bindEventListeners() {
    // 登录表单提交
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
    }
    
    // 登出按钮
    if (logoutBtn) {
        logoutBtn.addEventListener('click', handleLogout);
    }
    
    // 返回按钮
    if (backBtn) {
        backBtn.addEventListener('click', handleBack);
    }
    
    // 出库表单提交
    if (outboundForm) {
        outboundForm.addEventListener('submit', handleOutboundSubmit);
    }
    
    // 重置按钮
    if (resetBtn) {
        resetBtn.addEventListener('click', handleReset);
    }
}

// 设置默认日期
function setDefaultDate() {
    const today = new Date().toISOString().split('T')[0];
    if (expectedPickupDateInput) {
        expectedPickupDateInput.value = today;
    }
}

// 显示登录界面
function showLoginSection() {
    if (loginSection) loginSection.style.display = 'block';
    if (mainContent) mainContent.style.display = 'none';
}

// 显示主内容界面
function showMainContent() {
    if (loginSection) loginSection.style.display = 'none';
    if (mainContent) mainContent.style.display = 'block';
}

// 处理登录
function handleLogin(event) {
    event.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    
    fetch(`${API_BASE_URL}/auth/login`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            authToken = data.data.token;
            localStorage.setItem('authToken', authToken);
            showMainContent();
            setDefaultDate();
        } else {
            alert('登录失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('登录失败:', error);
        alert('登录失败');
    });
}

// 处理登出
function handleLogout() {
    authToken = null;
    localStorage.removeItem('authToken');
    showLoginSection();
}

// 处理返回
function handleBack() {
    window.location.href = '/'; // 返回主页
}

// 处理重置
function handleReset() {
    if (outboundForm) {
        outboundForm.reset();
        setDefaultDate();
    }
}

// 处理出库表单提交
function handleOutboundSubmit(event) {
    event.preventDefault();
    
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    const outboundData = {
        goodsId: parseInt(goodsIdInput.value),
        customer: customerInput.value,
        quantity: parseInt(quantityInput.value) || 1,
        expectedPickupDate: expectedPickupDateInput.value,
        operator: operatorInput.value,
        notes: notesInput.value
    };
    
    console.log('创建出库单据数据:', outboundData);
    
    fetch(`${API_BASE_URL}/outbound`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify(outboundData)
    })
    .then(response => response.json())
    .then(data => {
        console.log('出库单据创建响应:', data);
        if (data.success) {
            alert('出库单据创建成功');
            handleReset();
        } else {
            alert('出库单据创建失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('创建出库单据失败:', error);
        alert('创建出库单据失败');
    });
}